#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "winkill"
# Date: 2019/6/14


import jenkins
server = jenkins.Jenkins('http://127.0.0.1:8080', username="admin", password="Wgmf@1234!")

# server对象
# Jenkins的job数量
print(server.jobs_count())

# Jenkins-web-ui
#print(server.server)

# get all names of views
views = (server.get_views())
for viewname in views:
    print(viewname['name'])
# get job names from one view
jobs = server.get_jobs(view_name='mkt-back')
for jobsname in jobs:
    print(jobsname['name'])

# build jobs
server.build_job('test_mkt-back_build')
#queue_info = server.get_queue_info()
#id = queue_info[0].get('id')
#print(id)
#server.cancel_queue(id)
#server.build_job('test_bi-back_build')
#queue_info = server.get_queue_info()
#id = queue_info[0].get('id')

# 定时10秒
from time import sleep; sleep(10)

# create empty views
server.create_view('empty', jenkins.EMPTY_VIEW_CONFIG_XML)
#s = view_config = server.get_view_config('EMPTY')
#print(s)
#server.delete_view('empty')

# create empty job
#server.create_job('empty', jenkins.EMPTY_CONFIG_XML)

#my_job = server.get_job_config('empty')
#print(my_job)

# get status of build job
last_build_number = server.get_job_info('test_bi-back_build')['lastCompletedBuild']['number']
build_info = server.get_build_info('test_bi-back_build', last_build_number)
#print (build_info)
result = build_info['result']
print (result)

# groovy
# add jobs into views

groovycmd = '''
import hudson.model.*;
def job = Hudson.instance.getView("all").getItem("test_demo4_build");
Hudson.instance.getView("demo").add(job)
'''
server.run_script(groovycmd)

# remove jobs from views but not delete

groovycmd = '''
import hudson.model.*;
def job = Hudson.instance.getView("all").getItem("test_demo4_build");
Hudson.instance.getView("demo").remove(job)

